<template>
  <el-card class="global-card">
    <template #header>
      <div class="card-header">
        <span>公告管理</span>
        <el-button type="primary" :icon="Plus" @click="handleClickAdd"
          >添加</el-button
        >
      </div>
    </template>
    <AsideSearch
      :is-loading="loadOpts.refresh"
      @on-search="handleClickSearch"
    />
    <el-table
      :data="tableData"
      style="width: 100%; margin: 20px 0"
      border
      highlight-current-row
    >
      <el-table-column
        prop="title"
        label="标题"
        min-width="160"
        show-overflow-tooltip
      />
      <el-table-column prop="message" label="内容" show-overflow-tooltip />
      <el-table-column label="首页投放">
        <template #default="scope">
          <el-switch
            v-model="scope.row.state"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :loading="loadOpts.submit"
            :before-change="handleToggleSwitch.bind(null, scope.row, 'state')"
          />
        </template>
      </el-table-column>
      <el-table-column label="弹窗展示">
        <template #default="scope">
          <el-switch
            v-model="scope.row.isAlert"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :loading="loadOpts.submit"
            :before-change="handleToggleSwitch.bind(null, scope.row, 'isAlert')"
          />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" min-width="160">
        <template #default="scope">
          <PipeDatetime :value="scope.row.createTime || ''" />
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" min-width="144">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            link
            :icon="Edit"
            @click="handleClickRowEdit(scope.row)"
            >编辑</el-button
          >
          <el-popconfirm
            title="是否删除此数据?"
            confirm-button-text="确定"
            cancel-button-text="取消"
            :icon="InfoFilled"
            icon-color="red"
            :hide-after="0"
            @confirm="handleClickRowDel(scope.row.id)"
          >
            <template #reference>
              <el-button size="small" type="primary" link :icon="Delete"
                >删除</el-button
              >
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:currentPage="pageOpts.page.value"
      :page-sizes="pageOpts.sizes.value"
      :page-size="pageOpts.size.value"
      :layout="pageOpts.layout.value"
      :total="pageOpts.total.value"
      small
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    ></el-pagination>
  </el-card>

  <DrawerForm
    v-model="drawerOpts.visible"
    :title="drawerOpts.title"
    :size="drawerOpts.size"
    :is-edit="drawerOpts.isEdit"
    :row-data="drawerOpts.data"
    @on-refresh="requestData"
  />
</template>

<script setup lang="ts">
import { Plus, Edit, InfoFilled, Delete } from '@element-plus/icons-vue';
import { reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { cloneDeep } from 'lodash';

import { getNotifyList, updateSwitch, deleteNotify } from '@/apis/notify';
import { InitDrawerOpts, InitLoadOpts, InitPageOpts } from '@/utils/common';
// import { formatterEmptyString } from '@/utils/util';

import DrawerForm from './form.vue';
import AsideSearch from './aside-search.vue';

// 加载状态
const loadOpts = reactive(InitLoadOpts());

// 查询数据
let searchData: any;
const handleClickSearch = (data: any) => {
  searchData = data;
  requestData();
};

// 列表数据
let tableData = ref<API.notify.TableData[]>([]);

// 分页数据
const pageOpts = InitPageOpts({
  page: 1,
  size: 10
});

// 抽屉
const drawerOpts = reactive(InitDrawerOpts<API.notify.TableData | any>());

// 切换显示条数
const handleSizeChange = (size: number) => {
  pageOpts.size.value = size;
  pageOpts.page.value = 1;
  requestData();
};

// 切换页数
const handleCurrentChange = (page: number) => {
  pageOpts.page.value = page;
  requestData();
};

// 切换状态
const handleToggleSwitch = async (
  item: API.notify.EntitySchema,
  field: keyof API.notify.EntitySchema
): Promise<any> => {
  loadOpts.submit = true;
  try {
    const res = await updateSwitch(item.id!, {
      [field]: +!item[field]
    });
    loadOpts.submit = false;
    ElMessage.success(res.message);
    return Promise.resolve(true);
  } catch (err: any) {
    loadOpts.submit = false;
    return Promise.reject(new Error('Error'));
  }
};

// 添加
const handleClickAdd = () => {
  drawerOpts.title = '添加';
  drawerOpts.isEdit = false;
  drawerOpts.data = {
    urlList: []
  };
  drawerOpts.visible = !drawerOpts.visible;
};

// 编辑
const handleClickRowEdit = (row: API.notify.TableData) => {
  drawerOpts.title = '编辑';
  drawerOpts.isEdit = true;
  drawerOpts.data = cloneDeep(row);
  drawerOpts.visible = true;
};

// 删除
const handleClickRowDel = (id: number) => {
  if (loadOpts.submit) return;
  loadOpts.submit = true;

  deleteNotify(id)
    .then((res) => {
      loadOpts.submit = false;
      ElMessage.success(res.message);
      // 重新刷新数据
      pageOpts.page.value = 1;
      requestData();
    })
    .catch((err) => {
      loadOpts.submit = false;
      ElMessage.error(err.message);
    });
};

// 获取分页数据
const requestData = () => {
  const dataOpt = {
    page: pageOpts.page.value,
    limit: pageOpts.size.value,

    ...searchData
  };

  // 开始加载
  loadOpts.refresh = true;

  getNotifyList(dataOpt)
    .then((res) => {
      tableData.value = res.data.data || [];
      pageOpts.total.value = res.data.total;

      // 加载结束
      loadOpts.refresh = false;
    })
    .catch((err) => {
      console.log('table list error', err);
      // 加载结束
      loadOpts.refresh = false;
    });
};

requestData();
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
